﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Rison.BusinessFacade.Entity.XT;
using Rison.BusinessFacade.Facade.XT;

namespace Rison.Web.admin
{
    public partial class SysModules : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.labMsg.Text)) this.labMsg.Text = string.Empty;

            if (!this.IsPostBack)
            {
                this.btnDelete.Visible = false;//暂不提供该功能

                this.btnDelete.Attributes.Add("OnClick", "javascript:return window.confirm('确认删除所选的内容吗？');");

                VisibleGrid(true);

                BindProduct();
            }            
        }

        #region "  VisibleGrid  "
        private void VisibleGrid(bool bln)
        {
            this.gvProduct.Visible = bln;
            this.gvModules.Visible = !bln;
            if (bln)
                this.labMemu.Text = "";
        }
        #endregion


        #region"  绑定、显示数据  "
        private void BindProduct()
        {
            this.gvProduct.DataSource = new SysProductFacade().GetAllData();
            this.gvProduct.DataBind();
        }

        protected void gvProduct_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                VisibleGrid(false);
            }
            else if (e.CommandName == "Append")
            {
                SaveProduct(true);
            }
        }

        protected void gvProduct_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            this.labMemu.Text = (this.gvProduct.Rows[e.NewEditIndex].Cells[1].Controls[1] as TextBox).Text;

            this.labCurProductId.Text = this.gvProduct.DataKeys[e.NewEditIndex].Value.ToString();

            BindModules(this.labCurProductId.Text);
        }

        private void BindModules(string productId)
        {
            this.labCurProductId.Text = productId;
            DataSet modules = new SysModuleFacade().GetDataBy("ProductId=" + productId);
            if (modules.Tables[0].Rows.Count == 0)
            {
                this.labMemu.Text += "（尚未定义二级菜单）";

                DataRow row = modules.Tables[0].NewRow();
                row["MID"] = 0;
                row["Title"] = "未定义";
                row["Display"] = false;
                row["DisplayRows"] = 10;
                row["OrderId"] = 1;
                modules.Tables[0].Rows.Add(row);
            }

            this.gvModules.DataSource = modules;
            this.gvModules.DataBind();
        }

        protected void lbtnMunu_Click(object sender, EventArgs e)
        {
            VisibleGrid(true);
            BindProduct();
        }
        #endregion


        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(Request.RawUrl);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.gvProduct.Visible)
                SaveProduct(false);
            else
                SaveModules(false);

            if (string.IsNullOrEmpty(this.labMsg.Text))
                this.labMsg.Text = "保存完成！";
        }


        #region "  保存一级菜单  "
        private void SaveProduct(bool appendNew)
        {
            if (appendNew)
            {
                SaveProduct(this.gvProduct.FooterRow, null);               
            }
            else
            {
                SysProductFacade facade = new SysProductFacade();

                foreach (GridViewRow row in this.gvProduct.Rows)
                {
                    if (SaveProduct(row, facade) == false) break;
                }
            }

            if (string.IsNullOrEmpty(this.labMsg.Text))
                BindProduct();
        }

        private bool SaveProduct(GridViewRow row, SysProductFacade facade)
        {
            string pname = (row.Cells[1].Controls[1] as TextBox).Text;
            string orderid = (row.Cells[3].Controls[1] as TextBox).Text;
            string description = (row.Cells[4].Controls[1] as TextBox).Text;

            if (ValidateBasicInfo(pname, orderid, description))
            {
                SysProduct p = new SysProduct();
                p.PName = pname;
                p.OrderId = Convert.ToInt32(orderid);
                p.Description = description;
                p.Display = (row.Cells[2].Controls[1] as CheckBox).Checked;

                long returnValue = 0;
                if (facade == null)
                {
                    facade = new SysProductFacade();
                    returnValue = facade.Save(p);
                }
                else
                {
                    p.PID = Convert.ToInt32(this.gvProduct.DataKeys[row.RowIndex].Value);                
                    returnValue = facade.Update(p);
                }

                if (returnValue <= 0)
                    this.labMsg.Text = "保存错误！";
            }

            return string.IsNullOrEmpty(this.labMsg.Text);
        }

        private bool ValidateBasicInfo(string title,string orderId,string description)
        {
            if (title.Trim().Length == 0 || System.Text.Encoding.Default.GetByteCount(title) > 20)
                this.labMsg.Text = "标题不可为空且不能超过20个字符（10个汉字）！";
            else if (orderId.Trim().Length == 0)
                this.labMsg.Text = "请输入顺序号！";
            else if (System.Text.Encoding.Default.GetByteCount(title) > 500)
                this.labMsg.Text = "描述信息长度不能超过500个字符（250个汉字）！";

            return string.IsNullOrEmpty(this.labMsg.Text);
        }
        #endregion


        #region "  保存二级菜单  "
        protected void gvModules_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Append")
            {
                SaveModules(true);
            }
        }
        private void SaveModules(bool appendNew)
        {
            if (appendNew)
            {
                SaveModules(this.gvModules.FooterRow, null);
            }
            else
            {
                SysModuleFacade facade = new SysModuleFacade();

                foreach (GridViewRow row in this.gvModules.Rows)
                {
                    if (SaveModules(row, facade) == false) break;
                }
            }

            if (string.IsNullOrEmpty(this.labMsg.Text))
                BindModules(this.labCurProductId.Text);
        }
        private bool SaveModules(GridViewRow row, SysModuleFacade facade)
        {
            int colIndex = 3;//若标题图片列隐藏了，那么将需要修改该值
            string title = (row.Cells[1].Controls[1] as TextBox).Text;
            string rows = (row.Cells[colIndex + 1].Controls[1] as TextBox).Text;
            string orderid = (row.Cells[colIndex + 2].Controls[1] as TextBox).Text;
            string description = (row.Cells[colIndex + 3].Controls[1] as TextBox).Text;
            
            if (ValidateModule(title, rows, orderid, description))
            {
                SysModule m = new SysModule();
                m.ProductId = Convert.ToInt32(this.labCurProductId.Text);
                m.Title = title;
                m.OrderId = Convert.ToInt32(orderid);
                m.Display = (row.Cells[colIndex].Controls[1] as CheckBox).Checked;
                m.DisplayRows = Convert.ToInt32(rows);
                m.Description = description;

                long returnValue = 0;
                if (facade == null)
                {
                    facade = new SysModuleFacade();
                    returnValue = facade.Save(m);
                }
                else
                {
                    facade.ClearSqlFieldCollection();

                    m.MID = Convert.ToInt32(this.gvModules.DataKeys[row.RowIndex].Value);
                    if (m.MID > 0)
                        returnValue = facade.Update(m);
                    else
                        returnValue = facade.Save(m);
                }

                if (returnValue <= 0)
                    this.labMsg.Text = "保存错误！";
            }

            return string.IsNullOrEmpty(this.labMsg.Text);
        }

        private bool ValidateModule(string title, string rows, string orderId, string description)
        {
            if(this.ValidateBasicInfo(title,orderId,description ))
                if (rows.Trim().Length == 0)
                    this.labMsg.Text = "请输入显示行数！";

            return string.IsNullOrEmpty(this.labMsg.Text);
        }
        #endregion


        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //暂不提供该功能
        }

    }
}
